package com.example.springbootmybatisplusintegrat.user.bean;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author qrn
 * @Date 2024/4/27 16:49
 * @Version 1.0
 * @blog https://blog.csdn.net/qq_41971087
 */
@Slf4j
public class demo {

    public static void main(String[] args) {
        String fileName = "/Users/qurenneng/xiangmu/mayun/spring-boot-integrate/spring-boot-easyexcel-integrats/src/main/resources/DEVREQ-1896.csv";
        EasyExcel.read(fileName, ImportMsg.class, new ReadListener<ImportMsg>() {
            /**
             * 单次缓存的数据量
             */
            public static final int BATCH_COUNT = 1;
            /**
             * 临时存储
             */
            private List<ImportMsg> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(ImportMsg data, AnalysisContext context) {
                cachedDataList.add(data);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    saveData();
                    // 存储完成清理 list
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }

            /**
             * 加上存储数据库
             */
            private void saveData() {
                log.info("{}条数据，开始存储数据库！", cachedDataList.size());
                log.info("存储数据库成功！ data: {} ", JSON.toJSON(cachedDataList));
                return;
            }
        }).sheet().doRead();
    }
}
